from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
from util.myjwt import myjwt
from util.myrediss import r
import re
import time

class TokenAuthMiddleware(MiddlewareMixin):
    # 不需要验证token的路径列表
    white_list = [
        '/user/recharge/result/',
        '/essay/article-recommendation/',
        '/essay/es/search/',
        '/user/get_image_code/',
        '/user/send_verification_code/',
        '/user/login/',
        '/user/dd/',
        '/user/dd/callback/',
        '/uploads/users/d8ba61281d3b7b3df4f93d8bd06d9f6.png',
        '/background/doctors/',
        '/background/departments/',
        '/uploads/doctors/d8ba61281d3b7b3df4f93d8bd06d9f6.png',
        '/background/article-recommendation/',
        '/background/es/search/',
        '/user/essay/result/',
        '/essay/ai/medical-assistant/stream/',
        '/essay/ai/medical-assistant/demo/',
        '/background/schedules/',
        '/background/doctor-schedules/',
        '/background/time-slots/',
        'uploads', #图片相关的'
        '/ai/', # AI助手主页
        '/ai/api/initialize/', # AI助手初始化API
        '/ai/api/query/', # AI助手查询API
        '/ws/ai/', # AI助手WebSocket
        '/static/', # 静态文件路径
    ]

    def process_request(self, request):

        # 获取请求路径
        if request.path.startswith('/api/agent/'):
            return None
        path = request.path_info
        
        # 静态文件直接放行
        if path.startswith('/static/'):
            return None
            
        if path.startswith('/uploads/'):
            return None
        if path.startswith('/essay/'):
            return None
        # 如果是管理后台路径，直接放行，由AdminAuthMiddleware处理
        if path.startswith('/manage/'):
            return None
        
        # 新增：AI助手WebSocket路径不需要认证
        if path.startswith('/ws/ai/'):
            return None
            
        # 白名单路径直接放行
        if path in self.white_list:
            return None
            
        # 获取token
        token = request.headers.get('Authorization')
        if not token:
            return JsonResponse({'code': 401, 'message': '未登录'})
            
        # 验证token格式
        if not re.match(r'^Bearer\s+[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$', token):
            return JsonResponse({
                'code': 401,
                'message': 'token格式错误'
            })
            
        # 去掉Bearer前缀
        if token.startswith('Bearer '):
            token = token.split(' ')[1]
        
        # 验证token是否被修改
        try:
            payload = myjwt.decode(token)
            if not payload:
                return JsonResponse({
                    'code': 401,
                    'message': 'token无效'
                })
        except Exception as e:
            return JsonResponse({
                'code': 401,
                'message': 'token验证失败'
            })
            
        # 验证token是否过期
        if 'exp' in payload and payload['exp'] < time.time():
            return JsonResponse({
                'code': 401,
                'message': 'token已过期'
            })
            
        # 验证用户是否退出登录
        user_id = payload.get('userid')
        stored_token = r.get_value(f'user_token_{user_id}')
        if not stored_token or stored_token.decode() != token:
            return JsonResponse({
                'code': 401,
                'message': '用户已退出登录'
            })
            
        # 验证用户权限（这里简单示例，你可以根据实际需求扩展）
        # 例如：检查用户是否有权限访问特定路径
        if path.startswith('/admin/') and not payload.get('is_admin'):
            return JsonResponse({
                'code': 403,
                'message': '无权限访问'
            })
            
        # 将用户信息添加到request对象，方便视图函数使用
        request.user_info = payload
        
        return None 